package cn.jiedanba.itext.gm;

import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Signature;

import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalSignature;

/**
 * 国密 SM2私钥 P1签名
 * 
 * @author dell
 *
 */
public class Sm2PrivateKeySignature implements ExternalSignature {

	/** The private key object. */
	private PrivateKey pk;
	/** The hash algorithm. */
	private String hashAlgorithm;
	/** The encryption algorithm (obtained from the private key) */
	private String encryptionAlgorithm;
	/** The security provider */
	private String provider;

	public Sm2PrivateKeySignature(PrivateKey pk, String provider) {
		this.pk = pk;
		this.provider = provider;
		this.hashAlgorithm = DigestAlgorithms.getDigest(DigestAlgorithms.getAllowedDigests("SM3"));
		encryptionAlgorithm = "SM2";
	}

	@Override
	public String getHashAlgorithm() {
		return hashAlgorithm;
	}

	@Override
	public String getEncryptionAlgorithm() {
		return encryptionAlgorithm;
	}

	@Override
	public byte[] sign(byte[] message) throws GeneralSecurityException {
		String signMode = hashAlgorithm + "with" + encryptionAlgorithm;
		Signature sig;
		if (provider == null)
			sig = Signature.getInstance(signMode);
		else
			sig = Signature.getInstance(signMode, provider);
		sig.initSign(pk);
		sig.update(message);
		return sig.sign();
	}

}
